
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
 
public class ReadXmlFile {
 
  public static void main(String argv[]) {
 
    try {
 
	String fileName = "E:\\Nam4_HK2\\Java\\DoAnCuoiKi\\file.xml";
	File fXMLFile = new File(fileName);
	DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
	DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
	Document doc = dBuilder.parse(fXMLFile);
	doc.getDocumentElement().normalize();
	
	
	/*DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputStream inputStream= new FileInputStream(fileName);
    Reader reader = new InputStreamReader(inputStream,"UTF-8");
    InputSource input = new InputSource(reader);
    input.setEncoding("UTF-8");
    Document doc = builder.parse(input);*/
 
	System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
 
	NodeList nList = doc.getElementsByTagName("song");
 
	System.out.println("----------------------------");
 
	for (int temp = 0; temp < nList.getLength(); temp++) {
 
		Node nNode = nList.item(temp);
 
		System.out.println("\nCurrent Element :" + nNode.getNodeName());
 
		if (nNode.getNodeType() == Node.ELEMENT_NODE) {
 
			Element eElement = (Element) nNode;
			
			System.out.println("Name : " + eElement.getElementsByTagName("name").item(0).getTextContent());
			System.out.println("Author : " + eElement.getElementsByTagName("author").item(0).getTextContent());
			System.out.println("Id : " + eElement.getElementsByTagName("id").item(0).getTextContent());
			System.out.println("Lyric : " + eElement.getElementsByTagName("lyric").item(0).getTextContent());
			
		}
	}
    } catch (Exception e) {
	e.printStackTrace();
    }
  }
 
}
